<?php

namespace App\Jobs;

use App\Libraries\Tools\ConstVar;
use App\Libraries\Tools\Msg;
use App\Models\Order\Order;
use App\Models\Shop\ShopCouponPurchase;
use EasyWeChat\Payment\Payment;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class WechatRefundJob extends Job
{


    private $payment;
    private $purchase_model;
    private $order;
    private $user_id;

    /**
     * Create a new job instance.
     *
     * @param Payment $payment
     * @param Order $order
     * @param $purchase_model
     * @param $user_id
     */
    public function __construct(Payment $payment, Order $order,
                                $purchase_model, $user_id)
    {
        $this->payment = $payment;
        $this->order = $order;
        $this->purchase_model = $purchase_model;
        $this->user_id = $user_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $purchase = $this->purchase_model->where('id', $this->purchase_model->id)->first();
        $order = $this->order->where('id', $this->order->id)->first();
        if($purchase->status != ConstVar::$PURCHASE_STATUS_REFUNDING || $order->status != ConstVar::$ORDER_STATUS_REFUNDING){
            dispatch(new SendSystemMsgJob([$this->user_id], Msg::refund_reject(), 0));
            return ;
        }
        $result = $this->payment->refundByTransactionId($this->order->sid, $this->order->id, $this->order->receipt_amount * 100);
        if($result['return_code'] == 'SUCCESS'){
            $this->purchase_model->status = ConstVar::$PURCHASE_STATUS_REFUNDED;
            $this->order->status = ConstVar::$ORDER_STATUS_REFUNDED;
            $this->purchase_model->save();
            $this->order->save();
            dispatch(new SendSystemMsgJob([$this->user_id], Msg::refund_success(), 0));
        } else {
            $this->purchase_model->status = ConstVar::$PURCHASE_STATUS_UNUSED;
            $this->order->status = ConstVar::$ORDER_STATUS_SUCCESS;
            $this->purchase_model->save();
            $this->order->save();
            dispatch(new SendSystemMsgJob([$this->user_id], Msg::refund_fail(), 0));
        }
    }
}
